package cn.dliyy.warehouse.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.dliyy.warehouse.bean.BGoods;
import cn.dliyy.warehouse.bean.BUnit;
import cn.dliyy.warehouse.bean.BCategory;
import cn.dliyy.warehouse.bean.SStorage;
import cn.dliyy.warehouse.service.BGoodsService;
import cn.dliyy.warehouse.service.BCategoryService;
import cn.dliyy.warehouse.service.SStorageService;
import cn.dliyy.warehouse.service.BUnitService;
import cn.dliyy.warehouse.service.BWarehouseService;
import cn.dliyy.warehouse.validator.SStorageValidator;

@Controller
@RequestMapping(value = "/storage")
public class SStorageController {

  @Resource
  private SStorageService sStorageService;
  @Resource
  private SStorage sStorage;
  @Resource
  private BGoodsService bGoodsService;
  @Resource
  private BCategoryService categoryService;
  @Resource
  private BUnitService unitService;
  @Resource
  private BWarehouseService warehouseService;

  @RequestMapping(value = { "", "/" })
  public String load(ModelMap modelMap) {
    List<?> list = sStorageService.getList();
    modelMap.put("list", list);
    return "/storage/storage";
  }

  //@InitBinder
 // protected void initBinder(WebDataBinder binder) {
 //   binder.setValidator(new SStorageValidator());
 // }

  @RequestMapping(value = "/add", method = RequestMethod.GET)
  public String create(ModelMap modelMap) {
    sStorage = sStorageService.get();
    modelMap.addAttribute("storage", sStorage);
    modelMap.addAttribute("reasonMap", sStorage.getReasonMap());
    modelMap.addAttribute("warehouseList", warehouseService.getList());
    return "/storage/storage_add";
  }

  @RequestMapping(value = "/add", method = RequestMethod.POST)
  public String create(@Validated @ModelAttribute("storage") SStorage sStorage, BindingResult result, ModelMap modelMap) {
    if (result.hasErrors()) {
      sStorage = sStorageService.get();
      modelMap.addAttribute("reasonMap", sStorage.getReasonMap());
      modelMap.addAttribute("warehouseList", warehouseService.getList());
      return "/storage/storage_add";
    }
    validate( sStorage,result,modelMap);
    sStorageService.save(sStorage);
    return "redirect:/storage/";
  }

  @RequestMapping(value = { "/ajax/", "/ajax" })
  @ResponseBody
  public Map<String, Object> load(@RequestParam(value = "query") String name) {
    List<Object> bgoodlist = (List<Object>) bGoodsService.getListByName(name);
    if (bgoodlist == null || bgoodlist.size() == 0) {
      return null;
    }
    List<String> suggestions = new ArrayList<String>();
    List<SStorage> data = new ArrayList<SStorage>();
    Map<String, Object> map = new HashMap<String, Object>();
    for (int i = 0; i < bgoodlist.size(); i++) {
      StringBuffer s = new StringBuffer();
      BGoods bg = (BGoods) bgoodlist.get(i);
      BCategory tcate = (BCategory) categoryService.get(BCategory.class, bg.getCategoryId());
      BUnit tunit = (BUnit) this.unitService.get(bg.getUnitId());
      s.append(bg.getName());
      s.append(" ");
      s.append(bg.getSpecification());
      s.append(" ");
      s.append(tcate.getName());
      suggestions.add(s.toString());

      SStorage tsStorage = sStorageService.getLatest();// 获取最近一次的设置
      tsStorage.setCategory(tcate);// 更新为本次设置，此时的items等内容为最近一次的设置
      tsStorage.setUnit(tunit);
      tsStorage.setGoods(bg);

      data.add(tsStorage);
    }
    map.put("query", name);
    map.put("suggestions", suggestions);
    map.put("data", data);
    // return
    // "{query:'m',suggestions:['螺栓 M4','螺栓1 M4','aaaa M3'],data:['1','2','3']}";
    return map;
  }

  @RequestMapping(value = { "/ajax/goods" })
  @ResponseBody
  public SStorage load(@RequestParam(value = "name") String name, @RequestParam(value = "spec") String specification) {
    BGoods bg = bGoodsService.get(name, specification);
    if (bg == null) {
      return null;
    }

    BCategory tcate = (BCategory) categoryService.get(BCategory.class, bg.getCategoryId());
    BUnit tunit = (BUnit) this.unitService.get(bg.getUnitId());

    SStorage tsStorage = new SStorage();
    tsStorage.setCategory(tcate);
    tsStorage.setUnit(tunit);
    tsStorage.setGoods(bg);

    return tsStorage;
  }

  @RequestMapping(value = { "/validate/" })
  @ResponseBody
  public List<ObjectError> validate(@Valid @ModelAttribute("storage") SStorage sStorage, BindingResult result, ModelMap modelMap) {

    List<ObjectError> elist = result.getAllErrors();
    String goodsname=sStorage.getGoods().getName();
    String goodsspec=sStorage.getGoods().getSpecification();
    String goodspid=sStorage.getCategory().getId();
    
    if(true){
      
    }
    //return sStorage;
    return elist;
  }

  /**
   * 由于不显示的录入物品ID，因此需要对物品的名称，型号，所属分类来确定这一物品的唯一性； 1.如果没有此物品；
   * 2.物品名称型号分类与自动添加的物品ID所对应的名称等不一致。
   * 
   * @param bgoods
   */
  private void validateGoods(BGoods bgoods, Errors errors) {
    String goodsName = bgoods.getName();
    String goodsSpec = bgoods.getSpecification();
    String goodsCate = bgoods.getCategoryId();
    if (goodsName == null || "".equals(goodsName)) {
      errors.rejectValue("goods.name", "物品名称未填写");
    }
    if (goodsSpec == null || "".equals(goodsSpec)) {
      errors.rejectValue("goods.specification", "物品型号未填写");
    }
    if (goodsCate == null || "".equals(goodsCate)) {
      errors.rejectValue("category.name", "物品分类未填写");
    }

    bgoods.getName();

  }
}
